package com.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.activity.bean.OpusBean;
import com.api.param.AddWorkParam;
import com.api.param.RankParam;
import com.api.viewModel.LoginVM;
import com.baoyz.actionsheet.ActionSheet;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.widget.PictureEditView;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ToastUtil;
import com.example.lzbase.BaseViewModelActivity;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;
import event.MessageEvent;

public class OpusPostActivity extends BaseViewModelActivity<LoginVM> {


    @BindView(R.id.picture)
    PictureEditView picture;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_lab)
    TextView tvLab;
    @BindView(R.id.tagcontainerLayout1)
    TagContainerLayout tagcontainerLayout1;
    @BindView(R.id.ed_text)
    EditText edText;
    @BindView(R.id.tagcontainerLayout2)
    TagContainerLayout tagcontainerLayout2;
    @BindView(R.id.tv_zhuanji)
    TextView tvZhuanji;
    private ArrayList<String> selectString = new ArrayList<>();
    private OpusBean opus;
    private AddWorkParam param;
    private String id;

    @Override
    protected int titleText() {

        return R.string.post_opus;
    }

    private ArrayList<String> images = new ArrayList();
    private ArrayList<String> imageSizes = new ArrayList();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_opus_post;
    }

    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);
        Gson gson = new Gson();
        String json = null;
        if (getIntent().getExtras() != null)
            json = getIntent().getExtras().getString("param");
        if (json == null) {

        } else {
            opus = gson.fromJson(json, OpusBean.class);
        }

        if (opus == null) {

        } else {
            etTitle.setText(opus.getWorkstitle());
            etContent.setText(opus.getWorkscontent());
            imageSizes = new ArrayList(Arrays.asList(StringUtils.split(opus.getWorkssizes(), "|")));
            images = new ArrayList(Arrays.asList(StringUtils.split(opus.getWorkspics(), "|")));
            selectString = new ArrayList(Arrays.asList(StringUtils.split(opus.getWorkstags(), ",")));

            etContent.setSelection(opus.getWorkscontent().length());
            setTitleText("修改作品");
        }
        picture.setPictureAdapter(new PictureEditView.PictureAdapter() {
            @Override
            public int getItemCount() {
                return images.size();
            }

            @Override
            public ArrayList<String> data() {
                return images;
            }

            @Override
            public void deleteItem(int position) {
                images.remove(position);
                imageSizes.remove(position);
                picture.reload();
            }

            @Override
            public void clickItem(int position) {

//                ImageInfo imageInfo;
//                final List<ImageInfo> imageInfoList = new ArrayList<>();
//                for (String image : images) {
//                    imageInfo = new ImageInfo();
//                    imageInfo.setOriginUrl(image);// 原图url
//                    imageInfo.setThumbnailUrl(image);// 缩略图url
//                    imageInfoList.add(imageInfo);
//                }
//
//                ImagePreview
//                        .getInstance()
//                        // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
//                        .setContext(OpusPostActivity.this)
//                        .setIndex(position)
//                        .setImageList(images)
//                        .start();
//                GPreviewBuilder.from(OpusPostActivity.this)//activity实例必须
//                        .setData(mThumbViewInfoList)//集合
//                        .setCurrentIndex(position)
//                        .setSingleFling(true)//是否在黑屏区域点击返回
//                        .setDrag(true)//是否禁用图片拖拽返回
//                        .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
//                        .start();//启动

            }

            @Override
            public void clickTakePhoto() {
                ActionSheet.createBuilder(OpusPostActivity.this, getSupportFragmentManager())
                        .setCancelButtonTitle(getString(R.string.cacel))
                        .setOtherButtonTitles(getString(R.string.camera), getString(R.string.take_photo))
                        .setCancelableOnTouchOutside(true)
                        .setListener(new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                                if (index == 0) {
                                    PictureSelector.create(OpusPostActivity.this)
                                            .openCamera(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                            .maxSelectNum(1)// 最大图片选择数量 int
                                            .imageSpanCount(4)// 每行显示个数 int
                                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                            .previewImage(true)// 是否可预览图片 true or false
                                            .previewVideo(true)// 是否可预览视频 true or false
                                            .enablePreviewAudio(true) // 是否可播放音频 true or false
                                            .isCamera(true)// 是否显示拍照按钮 true or false
                                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                            .enableCrop(false)// 是否裁剪 true or false
                                            .withAspectRatio(3, 4)
                                            .compress(true)// 是否压缩 true or false
                                            .isGif(false)// 是否显示gif图片 true or false
                                            .hideBottomControls(false)
                                            .openClickSound(false)// 是否开启点击声音 true or false
                                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                } else {
                                    PictureSelector.create(OpusPostActivity.this)
                                            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                            .hideBottomControls(false)
                                            .maxSelectNum(1)// 最大图片选择数量 int
                                            .imageSpanCount(4)// 每行显示个数 int
                                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                            .previewImage(true)// 是否可预览图片 true or false
                                            .previewVideo(true)// 是否可预览视频 true or false
                                            .enablePreviewAudio(true) // 是否可播放音频 true or false
                                            .isCamera(true)// 是否显示拍照按钮 true or false
                                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                            .enableCrop(false)// 是否裁剪 true or false
                                            .withAspectRatio(3, 4)

                                            .compress(true)// 是否压缩 true or false
                                            .isGif(false)// 是否显示gif图片 true or false
                                            .openClickSound(false)// 是否开启点击声音 true or false
                                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                }
                            }
                        }).show();


            }

            @Override
            public String getItemUrl(int position) {
                return images.get(position);
            }

            @Override
            public Drawable getItemDrawable(int position) {
                return null;
            }
        });

        viewModel.addWork.observe(this, res -> {
            EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_ADD_WORKS));
            finish();

        });

        viewModel.updateWork.observe(this, res -> {
            Gson gson1 = new Gson();
            MessageEvent messageEvent = new MessageEvent(MessageEvent.MESSAGE_EVENT_ADD_WORKS);
            messageEvent.addwork = gson.toJson(param);
            EventBus.getDefault().post(messageEvent);
            finish();

        });

        tagcontainerLayout1.setTags(selectString);
        tagcontainerLayout1.setOnTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int position, String text) {

            }

            @Override
            public void onTagLongClick(final int position, String text) {

            }

            @Override
            public void onSelectedTagDrag(int position, String text) {
            }

            @Override
            public void onTagCrossClick(int position) {

                selectString.remove(position);
                tagcontainerLayout1.removeTag(position);

            }
        });
        tagcontainerLayout2.setOnTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int position, String text) {
                if (selectString.contains(text)) {
                    ToastUtil.toast(OpusPostActivity.this, R.string.biao_qian_cun_zai);

                } else {
                    tagcontainerLayout1.addTag(text);
                    selectString.add(text);


                }
            }

            @Override
            public void onTagLongClick(int position, String text) {

            }

            @Override
            public void onSelectedTagDrag(int position, String text) {

            }

            @Override
            public void onTagCrossClick(int position) {

            }
        });

        viewModel.tags.observe(this, res -> {

            ArrayList<String> datas = new ArrayList<>();
            for (int i = 0; i < res.size(); i++) {
                datas.add("#"+res.get(i).getTagname());
            }
            tagcontainerLayout2.setTags(datas);

        });
        RankParam param1 = new RankParam();
        param1.rank = App.getInstance().getAccount().getUserrank();

        if(StringUtils.isEmpty(param1.rank)){
            param1.rank="无";
        }

        addSubscription(viewModel.getTag(param1));

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000 && requestCode == 100) {
            tvLab.setText(data.getStringExtra("data"));
        }
        if (resultCode == 101 && requestCode == 1000) {
            tvZhuanji.setText(data.getStringExtra("name"));
            id = data.getStringExtra("id");
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);


                    ArrayList<String> arrayList = new ArrayList<>();
                    ArrayList<String> arraySize = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia media = selectList.get(i);
                        String path = media.getCompressPath();

                        arrayList.add(path);
                        arraySize.add(media.getWidth() + "," + media.getHeight());

                    }

                    viewModel.uplaodImages(arrayList, new LoginVM.ImageResult() {
                        @Override
                        public void result(ArrayList<String> result, ArrayList<String> origin) {

                            if (result.size() == 0)
                                return;


                            for (int i = 0; i < origin.size(); i++) {
                                if (origin.get(i).equals("")) {

                                } else {

                                    imageSizes.add(arraySize.get(arrayList.indexOf(origin.get(i))));
                                }
                            }

                            images.addAll(result);


                            picture.reload();
                        }
                    }, "works");
//                    picture.reload();

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }


    @OnClick({R.id.l_lab, R.id.btn_denglu})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.l_lab:

                Bundle bundle = new Bundle();
                bundle.putString("param", tvLab.getText().toString());
                ActivityUtil.startActivity(this, TagActivity.class, bundle, 100);

                break;
            case R.id.btn_denglu: {
                if (etTitle.getText().length() == 0) {
                    ToastUtil.toast(this, R.string.qing_shu_ru_zuo_pin_biao_ti);
                    return;
                }

                if (images.size() == 0) {
                    ToastUtil.toast(this, R.string.qing_tian_jia_pic);
                    return;
                }
                if (selectString.size() == 0) {
                    ToastUtil.toast(this, R.string.qing_tian_jia_biao_qian);
                    return;
                }
                param = new AddWorkParam();
                param.title = etTitle.getText().toString();
                param.content = etContent.getText().toString();
                param.tags = StringUtils.join(selectString, ",");
                param.pics = StringUtils.join(images, "|");
                param.sizes = StringUtils.join(imageSizes, "|");
                if(StringUtils.isEmpty(id)){
                    param.workscategoryid = "0";
                }else {
                    param.workscategoryid = id;
                }



                if (opus == null) {
                    addSubscription(viewModel.addworks(param));
                } else {

                    param.worksid = opus.getWorksid();
                    addSubscription(viewModel.updateworks(param));
                }
            }

            break;
        }
    }


    @OnClick(R.id.et_add)
    public void onClick() {

        if (edText.getText().toString().trim().length() == 0) {
            return;
        } else {

            if (selectString.contains(edText.getText().toString().trim())) {
                ToastUtil.toast(this, R.string.biao_qian_cun_zai);
                return;
            } else {
                tagcontainerLayout1.addTag("#"+edText.getText().toString().trim());
                selectString.add("#"+edText.getText().toString().trim());
                edText.setText("");

            }


        }
    }

    

    @OnClick(R.id.l_zhuanji)
    public void onViewClicked() {
        Bundle param=new Bundle();
        param.putBoolean("param", false);
        param.putString("super", "0");
        ActivityUtil.startActivity(this,CategoryActivity.class,param,1000);
    }

}
